package com.example.forum.service.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.User;
import com.example.forum.service.IUserService;
import com.example.forum.utils.JWTUtils;
import com.example.forum.utils.Md5Utils;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 注册用户
     * @param user
     */
    @Override
    public void createNormalUser(User user) {
        if(user == null
                || !StringUtils.hasLength(user.getUser_name())
                || !StringUtils.hasLength(user.getSalt())
                || !StringUtils.hasLength(user.getNickname())) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()));
        }

        User retUser = userMapper.selectByUserName(user.getUser_name());
        if(retUser != null) {
            log.error(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS.getMessage()));
        }

        //新增用户，设置默认自
        user.setGender(2);
        user.setArticle_count(0);
        user.setIs_admin(0);
        user.setState(0);
        user.setDelete_state(0);

        //当前日期
        Date date = new Date(System.currentTimeMillis());
        user.setCreate_time(date);
        user.setUpdate_time(date);
        Integer ret = userMapper.insert(user);
        if(ret == null || ret < 0) {
            log.error(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE.getMessage()));
        }
        log.info("新增用户成功，username:{}",user.getUser_name());
    }

    @Override
    public User login(String username,String password) {
        if(!StringUtils.hasLength(username)
                || !StringUtils.hasLength(password)) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessage() + ",username = " + username);
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()));
        }

        User retUser = userMapper.selectByUserName(username);
        if(retUser == null) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage() + ",username = " + username);
            throw new ApplicationException(ResultCode.FAILED_LOGIN.getMessage());
        }
        String finalPassword = Md5Utils.md5Salt(password,retUser.getSalt());

        if(!finalPassword.equals(retUser.getPassword())) {
           log.warn(ResultCode.FAILED_LOGIN.getMessage() + ",用户密码校验失败,username = " + username);
            throw new ApplicationException(ResultCode.FAILED_LOGIN.getMessage());
        }
        log.info("登陆成功,username = " + username);
        return retUser;
    }

    @Override
    public User getUserInfo(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        log.info("用户存在,username = " + user.getUser_name());

        if(user.getAvatar_url() != null) {
            Integer i = user.getAvatar_url().indexOf("image");
            if (i == null) {
                log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage());
                throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS.getMessage());
            }
            user.setAvatar_url("./" + user.getAvatar_url().substring(i));
        }
        return user;
    }

    @Override
    public Integer updateArticleCount(Article article) {
        if(article.getUser_id() < 0) {
            log.warn("参数校验失败");
            throw new ApplicationException("参数校验失败");
        }
        Long userId = article.getUser_id();
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null) {
            log.warn("用户不存在");
            throw new ApplicationException("用户不存在");
        }
        //看是否被禁言
        if(user.getState() == 1) {
            //为1被禁言
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        //设置每个用户所发的帖子数
        //如果一个Integer类型值为null在与int类型值相加时会进行自动拆包-调用intValue方法（由于是NULL，所以调用会报空指针异常）
        user.setArticle_count(user.getArticle_count()+1);
        //所以也直接将Integer类型改为int
        //user.setArticle_count(user.getArticle_count() + 1);
        Integer ret = userMapper.updateByPrimaryKeySelective(user);
        if(ret < 0 || ret == null) {
            log.warn("用户帖子数更新失败");
            throw new ApplicationException("用户帖子数更新失败");
        }
        log.info("用户帖子数更新成功");
        return ret;
    }

    @Override
    public Integer updateUser(User user) {
        Integer ret = userMapper.updateByPrimaryKeySelective(user);
        if(ret == null || ret <= 0) {
            log.warn("更新文章失败");
            throw new ApplicationException("更新文章失败");
        }
        log.info("更新文章成功");
        return ret;
    }

    @Override
    public Integer updateUserPassword(Long userId,String newPassword) {
        User user = userMapper.selectByPrimaryKey(userId);
        String finalPassword = Md5Utils.md5Salt(newPassword,user.getSalt());
        if(finalPassword == null) {
            log.warn("密码加密失败");
            throw new ApplicationException("密码加密失败");
        }
        user.setPassword(finalPassword);
        Integer ret = userMapper.updateByPrimaryKeySelective(user);
        if(ret == null) {
            log.warn("更改密码失败");
            throw new ApplicationException("更改密码失败");
        }
        return ret;
    }

    @Override
    public String loadUserPhoto(String filename, MultipartFile file,Long userId) {
        String pathName = "D:/tmp/Spring-Boot/forum/forum/src/main/resources/static/image/UserPhoto/" + filename;
        try {
            File newFile = new File(pathName);
            if(!newFile.exists()) {
                file.transferTo(newFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            log.warn("未找到用户");
            throw new ApplicationException("未找到用户");
        }
        user.setAvatar_url(pathName);
        Integer ret = userMapper.updateByPrimaryKeySelective(user);
        if (ret == null || ret <= 0) {
            log.warn("更新头像地址失败");
            throw new ApplicationException("更新头像地址失败");
        }

        Integer i = pathName.indexOf("image");
        if(i == null) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.getMessage());
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS.getMessage());
        }
        log.info("pathname:" + "./" + pathName.substring(i));
        return "./" + pathName.substring(i);

    }



}
